package logic

import (
	"encoding/json"
	"math"
	"strconv"
	"strings"
	"time"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
)

type Trc20Logic struct{}

const usdtTrc20ApiUri = "https://api.trongrid.io/v1/accounts/{address}/transactions/trc20"

// 代币，合约id
var usdtTrc20ContractId = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"

type TradeListResponse struct {
	Success bool        `json:"success"`
	Data    []TradeData `json:"data"`
}

type TradeData struct {
	TransactionID  string `json:"transaction_id"`
	Value          string `json:"value"`
	BlockTimestamp int64  `json:"block_timestamp"`
	From           string `json:"from"`
	To             string `json:"to"`
	Type           string `json:"type"`
}

// 获取转账列表
func (t *Trc20Logic) GetTradeList(address string) TradeListResponse {
	url := strings.Replace(usdtTrc20ApiUri, "{address}", address, 1)

	response, err := g.Client().Get(
		gctx.New(),
		url,
		g.Map{
			"contract_address": usdtTrc20ContractId,
			"only_confirmed":   true,
			"limit":            20,
			"start":            0,
		},
	)

	if err != nil {
		panic("获取转账列表失败")
	}
	defer response.Close()
	body := response.ReadAll()
	var tradeList TradeListResponse
	if err := json.Unmarshal(body, &tradeList); err != nil {
		panic("解析转账列表失败")
	}
	return tradeList
}

func (t *Trc20Logic) MatchTrade(wallet string, amount float64, createdAt *gtime.Time) bool {
	tradeResponse := t.GetTradeList(wallet)
	if tradeResponse.Success != true {
		return false
	}

	for _, item := range tradeResponse.Data {
		tradeAmount, err := strconv.ParseFloat(item.Value, 64)
		if err != nil {
			continue
		}
		tradeAmount = tradeAmount / 1000000

		tradeTime := createdAt.Time
		blockTime := time.Unix(item.BlockTimestamp, 0)
		timeDiff := tradeTime.Sub(blockTime)
		if tradeAmount == amount && math.Abs(timeDiff.Minutes()) <= 10 {
			return true
		}
	}
	return false
}
